import 'package:flutter/material.dart';
import 'package:flutter_draw/common/coordinate.dart';

class Paper extends StatefulWidget {
  const Paper({super.key});

  @override
  State<Paper> createState() => _PaperState();
}

class _PaperState extends State<Paper> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: CustomPaint(
        painter: PaperPainter(),
      ),
    );
  }
}

class PaperPainter extends CustomPainter {
  final Paint mPaint = Paint()
    ..style = PaintingStyle.fill
    ..color = Colors.blue
    ..strokeWidth = 0.5;
  final Path mPath = Path();
  final CoordinateWithText coordinate = CoordinateWithText(step: 25);

  final TextPainter _textPainter = TextPainter(
      text: const TextSpan(
          text: 'Hello Flutter',
          style: TextStyle(fontSize: 40, color: Colors.black)),
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr);

  @override
  void paint(Canvas canvas, Size size) {
    coordinate.paint(canvas, size);
    // 原点坐标移动到屏幕中心
    canvas.translate(size.width / 2, size.height / 2);

    //_drawTextPaint(canvas);
    //_drawTextPaintShowSize(canvas);
    _drawTextPaintWithPaint(canvas);
  }

  /// 绘制文字
  void _drawTextPaint(Canvas canvas) {
    // 绘制先设置 TextPainter，然后执行 layout() 方法进行布局，其中可以传入布局区域的最大和最小宽度。通过 paint 方法进行绘制。
    var textPainter = _textPainter;
    textPainter
      ..layout()
      ..paint(canvas, Offset.zero);
  }

  /// 获取文字范围
  //  TextPainter 中可以通过 size 属性获取文字所占区域，注意，获取区域必须在执行 layout 方法之后。
  // 一但确定范围后，就容易实现将文字中心绘制在画布原点，这一个效果是非常重要的。
  void _drawTextPaintShowSize(Canvas canvas) {
    TextPainter textPainter = _textPainter;

    textPainter.layout(); // 布局
    Size size = textPainter.size; // 尺寸必须在布局后获取
    textPainter.paint(canvas, Offset(-size.width / 2, -size.height / 2));

    canvas.drawRect(
        Rect.fromLTWH(0, 0, size.width, size.height)
            .translate(-size.width / 2, -size.height / 2),
        mPaint..color = Colors.blue.withAlpha(33));
  }

  /// 为文字设置画笔样式
  void _drawTextPaintWithPaint(Canvas canvas) {
    Paint textPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: 'Flutter Unit by Wonderful',
            style: TextStyle(foreground: textPaint, fontSize: 40)),
        textAlign: TextAlign.center,
        textDirection: TextDirection.ltr);
    textPainter.layout(maxWidth: 280);
    Size size = textPainter.size;
    textPainter.paint(canvas, Offset(-size.width / 2, -size.height / 2));

    canvas.drawRect(
        Rect.fromLTWH(0, 0, size.width, size.height)
            .translate(-size.width / 2, -size.height / 2),
        mPaint..color = Colors.blue.withAlpha(33));
  }

  // 为坐标系添加刻度

  @override
  bool shouldRepaint(PaperPainter oldDelegate) => false;
}
